import { useState, useEffect } from 'react';
import { 
  getConfig, 
  updateConfig, 
  validateConfig, 
  saveConfigToStorage, 
  loadConfigFromStorage,
  clearConfigFromStorage 
} from '../config/apiConfig';
import './ConfigPanel.css';

const ConfigPanel = ({ isOpen, onClose }) => {
  const [config, setConfig] = useState({
    baseUrl: '',
    endpoint: '',
    auth: {
      token: '',
      tenantId: ''
    },
    params: {
      agentId: '',
      threadId: ''
    }
  });
  const [errors, setErrors] = useState([]);
  const [isValid, setIsValid] = useState(false);

  useEffect(() => {
    if (isOpen) {
      // 加载当前配置
      loadConfigFromStorage();
      const currentConfig = getConfig();
      setConfig(currentConfig);
      validateCurrentConfig();
    }
  }, [isOpen]);

  const validateCurrentConfig = () => {
    const errors = [];
    
    if (!config.baseUrl) errors.push('baseUrl 不能为空');
    if (!config.endpoint) errors.push('endpoint 不能为空');
    if (!config.auth.token) errors.push('auth.token 不能为空');
    if (!config.auth.tenantId) errors.push('auth.tenantId 不能为空');
    if (!config.params.agentId) errors.push('params.agentId 不能为空');
    if (!config.params.threadId) errors.push('params.threadId 不能为空');
    
    setErrors(errors);
    setIsValid(errors.length === 0);
  };

  const handleInputChange = (field, value) => {
    const newConfig = { ...config };
    
    if (field.includes('.')) {
      const [parent, child] = field.split('.');
      newConfig[parent] = { ...newConfig[parent], [child]: value };
    } else {
      newConfig[field] = value;
    }
    
    setConfig(newConfig);
    
    // 延迟验证，避免频繁验证
    setTimeout(() => {
      validateCurrentConfig();
    }, 100);
  };

  const handleSave = () => {
    if (!isValid) {
      alert('请修复配置错误后再保存');
      return;
    }
    
    try {
      updateConfig(config);
      saveConfigToStorage();
      alert('配置保存成功！');
      onClose();
    } catch (error) {
      console.error('保存配置失败:', error);
      alert('保存配置失败，请检查控制台错误信息');
    }
  };

  const handleReset = () => {
    if (window.confirm('确定要重置为默认配置吗？')) {
      clearConfigFromStorage();
      const defaultConfig = getConfig();
      setConfig(defaultConfig);
      validateCurrentConfig();
    }
  };

  const handleTestConnection = async () => {
    if (!isValid) {
      alert('请先修复配置错误');
      return;
    }
    
    try {
      const testUrl = `${config.baseUrl}${config.endpoint}?query=test&agentId=${config.params.agentId}&threadId=${config.params.threadId}`;
      const response = await fetch(testUrl, {
        method: 'GET',
        headers: {
          'authorization': `Bearer ${config.auth.token}`,
          'tenant-id': config.auth.tenantId,
          'Accept': '*/*',
          'User-Agent': 'AI-Chat-Client/1.0.0',
          'Connection': 'keep-alive'
        }
      });
      
      if (response.ok) {
        alert('连接测试成功！');
      } else {
        alert(`连接测试失败: ${response.status} ${response.statusText}`);
      }
    } catch (error) {
      alert(`连接测试失败: ${error.message}`);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="config-panel-overlay">
      <div className="config-panel">
        <div className="config-header">
          <h3>API配置</h3>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        
        <div className="config-content">
          <div className="config-section">
            <h4>基础配置</h4>
            <div className="form-group">
              <label>Base URL:</label>
              <input
                type="text"
                value={config.baseUrl}
                onChange={(e) => handleInputChange('baseUrl', e.target.value)}
                placeholder="http://localhost:48080"
              />
            </div>
            <div className="form-group">
              <label>Endpoint:</label>
              <input
                type="text"
                value={config.endpoint}
                onChange={(e) => handleInputChange('endpoint', e.target.value)}
                placeholder="/admin-api/graph/stream/search"
              />
            </div>
          </div>
          
          <div className="config-section">
            <h4>认证信息</h4>
            <div className="form-group">
              <label>Token:</label>
              <input
                type="text"
                value={config.auth.token}
                onChange={(e) => handleInputChange('auth.token', e.target.value)}
                placeholder="Bearer token"
              />
            </div>
            <div className="form-group">
              <label>Tenant ID:</label>
              <input
                type="text"
                value={config.auth.tenantId}
                onChange={(e) => handleInputChange('auth.tenantId', e.target.value)}
                placeholder="1"
              />
            </div>
          </div>
          
          <div className="config-section">
            <h4>请求参数</h4>
            <div className="form-group">
              <label>Agent ID:</label>
              <input
                type="text"
                value={config.params.agentId}
                onChange={(e) => handleInputChange('params.agentId', e.target.value)}
                placeholder="1"
              />
            </div>
            <div className="form-group">
              <label>Thread ID:</label>
              <input
                type="text"
                value={config.params.threadId}
                onChange={(e) => handleInputChange('params.threadId', e.target.value)}
                placeholder="11"
              />
            </div>
          </div>
          
          {errors.length > 0 && (
            <div className="config-errors">
              <h4>配置错误:</h4>
              <ul>
                {errors.map((error, index) => (
                  <li key={index}>{error}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
        
        <div className="config-footer">
          <button 
            className="btn btn-secondary" 
            onClick={handleReset}
          >
            重置
          </button>
          <button 
            className="btn btn-primary" 
            onClick={handleTestConnection}
            disabled={!isValid}
          >
            测试连接
          </button>
          <button 
            className="btn btn-primary" 
            onClick={handleSave}
            disabled={!isValid}
          >
            保存
          </button>
        </div>
      </div>
    </div>
  );
};

export default ConfigPanel;
